import _ from 'lodash';
import { Loading } from 'element-ui';

export default class LoadingInstance {
  constructor() {
    // loading
    this.loading = null;
    // 当前请求条数
    this.count = 0;
    // 延时时间
    this.loadingDelay = 800;
    // 延时loading数组
    this.requestLoadingIdList = [];
    // 防抖-合并300ms内的隐藏loading 防止loading闪烁
    this.debounceHideLoading = _.debounce(() => {
      if (this.loading) {
        this.loading.close();
        this.loading = null;
      }
    }, 300);
  }

  /**
   * 显示loading
   * @param {*} text 加载提示文字
   * @param {*} target 加载目标元素
   */
  showLoading(text, target = 'body') {
    if (this.count === 0 && !this.loading) {
      this.loading = Loading.service({
        lock: true,
        spinner: 'el-icon-loading',
        customClass: 'custom-loading',
        text,
        background: 'rgba(0, 0, 0, 0.5)',
        target
      });
    }
    this.count++;
  }

  /**
   * 隐藏loading
   */
  hideLoading() {
    if (this.count > 0) {
      this.count--;
    }

    // 防止请求数量小于0，做个0值保护
    this.count = Math.max(this.count, 0);

    if (this.count === 0) {
      this.debounceHideLoading();
    }
  }

  /**
   * 清除延时显示的loading
   * @param {*} url 请求地址
   * @param {*} retainLastOne 保留最后一次的重复请求 true是 false否
   */
  clearTimeoutForLoading(retainLastOne) {
    let copyRequestLoadingIdList = _.cloneDeep(this.requestLoadingIdList);
    if (retainLastOne) {
      copyRequestLoadingIdList.length =
        copyRequestLoadingIdList.length > 0 ? copyRequestLoadingIdList.length - 1 : copyRequestLoadingIdList.length;
    }
    copyRequestLoadingIdList.map((item, index) => {
      clearTimeout(item.loadingId);
      copyRequestLoadingIdList.splice(index, 1);
      this.requestLoadingIdList.splice(index, 1);
    });

    if (this.requestLoadingIdList.length === 0) {
      this.count = 0;
    }
  }
}
